import { constantRouterMap } from '@/router/index.js'
import router from '@/router'
/* Layout */
import Layout from '@/views/layout/Layout'
import store from '../index'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { roles } = data
        store.getters.menu_list.forEach(item => {
          var obj = { meta: {}}
          obj.path = `/${item.path}`
          obj.component = resolve => require([`@/views/` + item.component + `.vue`], resolve)
          obj.name = item.name
          obj.meta.title = item.title
          obj.meta.icon = item.icon
          if (item.sub_menu) {
            obj.children = []
            item.sub_menu.forEach(subItem => {
              var subObj = { meta: {}}
              subObj.path = subItem.path
              subObj.component = resolve => require([`@/views/` + subItem.component + `.vue`], resolve)
              subObj.name = subItem.name
              subObj.meta.title = subItem.title
              subObj.meta.icon = subItem.icon
              obj.children.push(subObj)
            })
          }
          constantRouterMap.push(obj)
        })
        // router.addRoutes(newRouter)
        commit('SET_ROUTERS', constantRouterMap)
        resolve()
      })
    }
  }
}

export default permission
